﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;

namespace XLS2DBF
{
    public partial class XLS2DBF : Form
    {
        public XLS2DBF()
        {
            InitializeComponent();
        }

        private void XLS2DBF_DragEnter(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            textBox1.Text = path;
        }

        private void iopen_Click(object sender, EventArgs e)
        {
            OpenFileDialog ixls = new OpenFileDialog();
            ixls.Filter = "Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx";
            if (ixls.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = ixls.FileName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length == 0)
            {
                MessageBox.Show("Error");
            }
            else
            {
                object path = textBox1.Text;
                object savepath = textBox1.Text + ".dbf";
                object missing = System.Reflection.Missing.Value;
                Excel._Application ixls = new Excel.Application();
                ixls.Visible = true;
                Excel._Workbook wbook = (Excel._Workbook)ixls.Workbooks.Open((string)path, true, true);
                Excel._Worksheet wsheet = (Excel._Worksheet)wbook.Worksheets[1];

                string strcol;
                string strow;
                //datas
                int col = 1;
                do
                {
                    strcol = wsheet.get_Range("A" + col.ToString(), "A" + col.ToString()).Text.ToString();
                    col++;
                }
                while (strcol.Length != 0);

                //nature
                num2char ichange = new num2char();
                int row = 1;
                do
                {
                    strow = wsheet.get_Range(ichange.numchar(row) + "1", ichange.numchar(row) + "1").Text.ToString();
                    row++;
                }
                while (strow.Length != 0);

                string char1 = ichange.numchar(row - 2);

                Excel.Range xlWork = wsheet.get_Range("A1:" + char1.ToString() + (col - 2).ToString());
                xlWork.Select();
                wbook.SaveAs((string)savepath, Excel.XlFileFormat.xlDBF4, true, true);
                wbook.Close(true);
                ixls.Quit();
            }
        }
    }
}
